<template>
    <div>
        <!-- <el-button @click="router.push('/roleInsertInfo')">角色添加</el-button> -->
        <el-table :data="roleList" border>
            <el-table-column type="index" :index="indexMethod" min-width="30" label="编号" align="center" />
            <el-table-column label="角色名称" prop="roleName" align="center">
                <template #default="scope">
                    <el-link @click="changeRole(scope.row.roleId, scope.row.roleName)">{{ scope.row.roleName
                        }}</el-link>
                </template>
            </el-table-column>
            <el-table-column label="创建人" prop="createPerson" align="center"></el-table-column>
            <el-table-column label="创建日期" prop="createDate" align="center">
                <template #default="scope">
                    {{ scope.row.createDate.substr(0, 10) + " " + scope.row.createDate.substr(11, 8) }}
                </template>
            </el-table-column>
            <el-table-column label="修改人" prop="revisePerson" align="center"></el-table-column>
            <el-table-column label="修改日期" prop="reviseDate" align="center">
                <template #default="scope">
                    {{ scope.row.reviseDate ? scope.row.reviseDate.substring(0, 19).split("T")[0] + " "
                        + scope.row.reviseDate.substring(0, 19).split("T")[1] : "" }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200px" align="center">
                <template #default="scope">
                    <el-link @click="updateRoleInfo(scope.row.roleId)">修改</el-link>
                    &ensp;|&ensp;
                    <el-link @click="logicDelete(scope.row.roleId)">删除</el-link>
                    &ensp;|&ensp;
                    <el-link @click="AssignedPersonnel(scope.row.roleId, scope.row.roleName)">分配人员</el-link>
                </template>
            </el-table-column>
        </el-table>
        <table style="margin: 10px auto;">
            <tr>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, sizes" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        共 {{ page.totalCount }} 条，共 {{ page.pageCount }} 页，当前 {{ page.index }} / {{ page.pageCount }} 页
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, prev, pager, next" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                        next-text="下一页">
                        <el-button :disabled="page.index == 1" @click="handleCurrentChange(1)">首页</el-button>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, jumper" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        <el-button :disabled="page.index == page.pageCount"
                            @click="handleCurrentChange(page.pageCount)">尾页</el-button>
                    </el-pagination>
                </td>
            </tr>
        </table>
        <!-- 角色添加弹框 -->
        <el-dialog v-model="dialogVisibleRoleInsert" title="角色添加" width="500">
            <RoleInsert></RoleInsert>
        </el-dialog>
        <!-- 分配人员添加弹框 -->
        <el-dialog v-model="dialogVisibleAssignedPersonnel" width="500">
            <template #header>
                请设置 <span style="color: red;font-size: 20px;">【{{ rName }}】</span> 角色的员工
            </template>
            <el-row>
                <el-col :span="12">
                    <el-tree style="max-width: 600px" :data="data" show-checkbox default-expand-all node-key="id"
                        highlight-current :props="defaultProps" getCheckedKeys :expand-on-click-node="false"
                        @node-click="handleNodeClick" />
                </el-col>
                <el-col :span="12">
                    <el-tree ref="treeRef" style="max-width: 600px" :data="userTree" show-checkbox default-expand-all
                        node-key="id" highlight-current :props="defaultProps" getCheckedKeys
                        :expand-on-click-node="false" @check="handleCheck" />
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <p style="float: right;">
                        <el-button @click="saveSelUser()">
                            确定保存
                        </el-button>
                    </p>
                </el-col>
            </el-row>
        </el-dialog>
        <!-- 点击角色名称弹框 -->
        <el-dialog v-model="dialogVisibleRoleAdd" width="500">
            <template #header>
                属于 <span style="color: red;font-size: 20px;">【{{ rName }}】</span> 角色的员工如下
            </template>
            <el-tag style="margin-right:10px;" v-for="item in userRoleInfo" :key="item.userId" closable
                @close="deleteUserRole(item.userId)">
                {{ item.userName }}
            </el-tag>
            <el-tag type="success">
                <el-icon @click="AssignedPersonnel(rId, rName)">
                    <Plus />
                </el-icon>
            </el-tag>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
// 引入组件
import { ref, reactive, onMounted, inject } from 'vue'
import RoleInsert from '../Role/RoleInsertInfo.vue'
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage, ElTree } from 'element-plus'
import type { TreeKey } from 'element-plus/es/components/tree/src/tree.type.mjs';

// 定义变量
import http from '@/http'
const router = useRouter()

// 序号
const indexMethod = (index: number) => {
    return index += (page.size) * (page.index - 1) + 1;
}

// 分页条件
const page = reactive({
    size: 15,
    index: 1,
    totalCount: 0,
    pageCount: 0
})

// 角色列表
const roleList = ref([])

// 获取角色列表
const getRoleList = () => {
    http.get("/api/Role/GetRoleList", {
        params: {
            size: page.size,
            index: page.index
        }
    }).then(res => {
        roleList.value = res.data.datas;
        page.pageCount = res.data.pageCount;
        page.totalCount = res.data.totalCount;
    })
}

// 分页事件（改变页容量、改变页索引）
const handleSizeChange = (val: number) => {
    page.size = val;
    getRoleList();
}
const handleCurrentChange = (val: number) => {
    page.index = val;
    getRoleList();
}

// 修改角色信息
const updateRoleInfo = (roleId: number) => {
    router.push('/roleUpdateInfo?roleId=' + roleId);
}

// 逻辑删除角色信息
const logicDelete = (roleId: number) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示信息',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.delete("/api/Role/LogicDelete?roleId=" + roleId).then(res => {
                if (res.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                        duration: 500
                    });
                    getRoleList();
                }
                else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败',
                        duration: 500
                    })
                }
            })
        })
}

// 角色添加弹框显示
const dialogVisibleRoleInsert = ref(false)
// 分配员工弹框显示
const dialogVisibleAssignedPersonnel = ref(false)

// 角色Id
const rId = ref(0)
// 角色名称
const rName = ref("")
// 分配员工点击事件
const AssignedPersonnel = (roleId: number, roleName: string) => {
    // 初始化角色Id和角色名称
    rId.value = roleId;
    rName.value = roleName;
    // 分配员工弹框显示
    dialogVisibleAssignedPersonnel.value = true;
    rName.value = roleName;
    // 分配员工默认显示所有员工
    getUserTreeList(0);
    // 获取该角色下的员工列表
    getUserListByRoleAdd();
    showUserRoleInfo();
}

// 树形结构属性
const defaultProps = {
    children: 'children',
    label: 'label',
}
interface Tree {
    id: number
    label: string
    children?: Tree[]
}
// 部门树形结构数据
const data: Tree[] = [
    {
        id: 0,
        label: '请选择部门',
        children: [
            {
                id: 1,
                label: 'IT资源部',
            },
            {
                id: 2,
                label: '人力资源部',
            },
            {
                id: 3,
                label: '财务部',
            },
            {
                id: 4,
                label: '销售部',
            },
            {
                id: 5,
                label: '行政部',
            },
        ],
    },
]

// 根据部门Id获取用户列表
const userTree = ref<Tree[]>([])
const getUserTreeList = (departmentId: number) => {
    http.get("/api/Role/GetUserTreeListByDepartmentId?departmentId=" + departmentId).then(res => {
        userTree.value = [];
        userTree.value.push({
            id: 0,
            label: '请选择员工',
            children: res.data
        });
    })
    showUserRoleInfo();
}

// 员工列表复选框点击事件
const handleCheck = (data: any) => {
    let index = selUserAll.value.indexOf(data.id);
    if (index > -1) selUserAll.value.splice(index, 1);
}

// 选中用户数组
const selUser = ref<TreeKey[]>([])
const selUserAll = ref<TreeKey[]>([])
// 部门树形结构点击事件
const treeRef = ref<InstanceType<typeof ElTree>>()
const handleNodeClick = (data: Tree) => {
    let departmentId = data.id;
    // 获取该部门下的员工列表
    getUserTreeList(departmentId);

    // 获取选中的员工列表并去重
    selUserAll.value = Array.from(new Set(selUserAll.value.concat(treeRef.value!.getCheckedKeys(false))));
    console.log(selUserAll.value)
    treeRef.value!.setCheckedKeys(selUserAll.value, true);
}


const saveSelUser = () => {
    selUser.value = treeRef.value!.getCheckedKeys(false);
    // 获取选中的员工列表并去重
    selUserAll.value = Array.from(new Set(selUserAll.value.concat(selUser.value)));
    console.log(selUser.value);
    // 员工角色添加
    let info = ({
        roleId: rId.value,
        userIds: selUserAll.value
    })
    // 调用后台接口完成添加功能
    http.post("/api/Role/UserRoleBatchInsert", info).then(res => {
        if (res.data > 0) {
            ElMessage({
                type: 'success',
                message: '保存成功',
                duration: 1000
            });
            getUserListByRoleAdd();
            // 添加完成后取消弹框显示
            dialogVisibleAssignedPersonnel.value = false;
        }
        else {
            ElMessage({
                type: 'error',
                message: '保存失败',
                duration: 1000
            })
        }
    })
}

// 角色名称点击事件
const dialogVisibleRoleAdd = ref(false)
const changeRole = (roleId: number, roleName: string) => {
    rId.value = roleId;
    rName.value = roleName;
    dialogVisibleRoleAdd.value = true;
    getUserListByRoleAdd();
}

// 获取某角色下的用户列表
const userRoleInfo = ref<{
    userId: number,
    userName: string
}[]>([])
const getUserListByRoleAdd = () => {
    http.get("/api/Role/GetUserListByRoleId?roleId=" + rId.value).then(res => {
        selUserAll.value = [];
        userRoleInfo.value = res.data;
        userRoleInfo.value.forEach(ele => {
            selUserAll.value.push(ele.userId);
        });
        if (dialogVisibleAssignedPersonnel.value == true) {
            showUserRoleInfo();
        }
    })
}

// 删除角色下的单个用户
const deleteUserRole = (userId: number) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示信息',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.delete("/api/Role/DeleteUserRoleInfo", {
                params: {
                    roleId: rId.value,
                    userId: userId
                }
            }).then(res => {
                if (res.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                        duration: 1000
                    });
                    getUserListByRoleAdd();
                }
                else {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                        duration: 1000
                    })
                }
            })
        })
}

// 员工角色回显
const showUserRoleInfo = () => {
    setTimeout(() => {
        // 该角色下的用户列表回显
        treeRef.value!.setCheckedKeys(selUserAll.value, false);
    }, 10);
}

// 钩子函数
onMounted(() => {
    getRoleList();
})
</script>

<style scoped></style>